package com.whq.knowverywell.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.whq.knowverywell.R;
import com.whq.knowverywell.business.http.LoginUtil;
import com.whq.knowverywell.util.TipUtil;

/**
 * 登录
 * @author wanghuaiqiang
 *
 */
public class LoginActivity extends BaseActivity {
	private EditText mEtGroupCode = null;
	private EditText mEtUserName = null;
	private EditText mEtPassword = null;
	
	private ImageView mIvChkboxRememberPwd = null;
	private boolean mRememberMe = true;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_Sherlock_Light_NoActionBar);
		setContentView(R.layout.login);
		
		Button btnLogin = (Button) findViewById(R.id.btn_login);
		btnLogin.setOnClickListener(this);
		
		mEtGroupCode = (EditText) findViewById(R.id.et_groupCode);
		mEtUserName = (EditText) findViewById(R.id.et_userName);
		mEtPassword = (EditText) findViewById(R.id.et_password);
		mIvChkboxRememberPwd = (ImageView) findViewById(R.id.iv_chkbox_remember_pwd);
		mIvChkboxRememberPwd.setOnClickListener(this);
		
		if (LoginUtil.chkLogin(this)) {
    		Intent intent = new Intent(this, HomeActivity.class);
    		startActivity(intent);
    		this.finish();
    		return ;
    	}
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		
		switch (v.getId()) {
		case R.id.btn_login:
			if (mLoadProgressDialog != null) {
				mLoadProgressDialog.setMessage("正在登录...");
			}
			this.openProgressDialog();
			new LoginTask().execute();
			break;
		case R.id.iv_chkbox_remember_pwd:
			chgRememberMeStatus();
			break;
		}
	}
	
	private void chgRememberMeStatus() {
		mRememberMe = !mRememberMe;
		if (mRememberMe) {
			mIvChkboxRememberPwd.setImageResource(R.drawable.checkbox_checked);
		} else {
			mIvChkboxRememberPwd.setImageResource(R.drawable.checkbox_not_check);
		}
	}
	
	private void handleLoginResult(boolean result) {
		this.closeProgressDialog();
		if (result) {
			TipUtil.tipDescription(this, "登录成功！");
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
		} else {
			TipUtil.tipDescription(this, "登录失败！");
		}
	}
	
	class LoginTask extends AsyncTask<String, String, String> {
		private boolean loginOk = false;
		
		@Override
		public String doInBackground(String... params) {
			String groupCode = mEtGroupCode.getText().toString();
			String userName = mEtUserName.getText().toString();
			String password = mEtPassword.getText().toString();
			
			this.loginOk = LoginUtil.login(LoginActivity.this, groupCode, userName, password, mRememberMe);
			return null;
		}
		
		@Override
		public void onPostExecute(String result) {
			handleLoginResult(this.loginOk);
		}
	}
}
